package core

import (
	"bytes"
	"errors"
	"logengine/model"
	"strconv"
	"time"
)

func DataTransform(filetime time.Time, fileData []byte, symbol string) (model.BatchMessageData, error) {
	// const aa int = '\r'
	arr := bytes.Split(fileData, []byte{'\r', '\n'}) // \r \n
	if len(arr) < 2 {
		return nil, errors.New("file_data_is_err")
	}
	//
	arr = arr[1:]
	msgDatas := make(model.BatchMessageData, 0, len(arr))

	start := filetime.Add(-24 * time.Hour)
	end := filetime.Add(-24 * time.Hour)
	//
	for _, row := range arr {
		// 非 0;6;开头全部排除掉
		if !bytes.HasPrefix(row, []byte("0;6;")) {
			continue
		}

		if bytes.HasPrefix(row, []byte("0;6;68;")) {
			aa := row[7:17]
			t1, _ := time.Parse("2006-01-02", string(aa))
			if t1.Before(start) || t1.After(end) {
				continue
			}
		}

		if bytes.HasPrefix(row, []byte("0;6;1;")) {
			aa := row[6:16]
			t1, _ := time.Parse("2006-01-02", string(aa))
			if t1.Before(start) || t1.After(end) {
				continue
			}
		}
		// {DataAddr: "-1", Result: string(row)},
		dataArray := []model.Report{
			{DataAddr: symbol, Result: string(row)},
		}
		//
		message := new(model.MessageData)
		message.Datas = dataArray
		msgDatas = append(msgDatas, message)
		//
	}
	return msgDatas, nil
}

func oldDataTransform(fileData []byte) (model.BatchMessageData, error) {
	// const aa int = '\r'
	arr := bytes.Split(fileData, []byte{'\r', '\n'}) // \r \n
	if len(arr) < 2 {
		return nil, errors.New("file data is err")
	}
	//
	arr = arr[1:]

	msgDatas := make(model.BatchMessageData, 0, len(arr))
	//
	for _, row := range arr {
		// 非 0;6;开头全部排除掉
		if !bytes.HasPrefix(row, []byte("0;6;")) {
			continue
		}
		// 从第一列开始
		cols := bytes.Split(row, []byte{';'})
		datas := make([]model.Report, 0, len(cols))
		for ii, col := range cols {
			datas = append(datas, model.Report{
				DataAddr: strconv.Itoa(ii + 1),
				Result:   string(col),
			})
		}
		datas = append(datas, model.Report{
			DataAddr: "-1", // 模次记录
			Result:   string(row),
		})
		//
		message := new(model.MessageData)
		message.Datas = datas
		msgDatas = append(msgDatas, message)
		//
	}
	return msgDatas, nil
}
